package core

import (
	"context"
	"github.com/nats-io/nats.go/micro"
)
import (
	"errors"
	"fmt"
)

const (
	RequestIDKey = "X-Request-ID"
	UserIDKey    = "X-User-ID"
)

var MetaKeys = []string{
	// request id
	RequestIDKey,
	// current user id
	UserIDKey,
}

func GetStringFromContext(ctx context.Context, key string) (result string, err error) {
	result, ok := ctx.Value(key).(string)
	if !ok {
		return "", errors.New(fmt.Sprintf("can not find [%s] from context", key))
	}
	return result, nil
}

func SetStringToContext(ctx context.Context, k, v string) context.Context {
	newCtx := context.WithValue(ctx, k, v)
	return newCtx
}

func GetContextFromNatsMicroRequest(ctx context.Context, request micro.Request) context.Context {

	for k, _ := range request.Headers() {
		if request.Headers().Get(k) != "" {
			ctx = context.WithValue(ctx, k, request.Headers().Get(k))
		}
	}

	return ctx
}
